package com.xiaoai.juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 * 独占锁（写锁） 一次只能被一个线程占有
 * 共享锁 (读锁) 一次可以被多个线程同时占有
 *
 * 读-读 可共存
 * 读-写
 * 写-写
 * @Author
 * @Date 2021-09-21 22:43
 */
public class ReadWriteLockDemo {
    public static void main(String[] args){
//        MyCache myCache = new MyCache();
        MyCacheLock myCacheLock = new MyCacheLock();
        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(
                () -> {
                    myCacheLock.put(temp+"" , temp+"");
                }
            ).start();
        }

        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(
                () -> {
                    myCacheLock.get(temp+"");
                }
            ).start();
        }

    }
}

/**
 * 自定义缓存
 */
class MyCache{
    private volatile Map<String,Object> map = new HashMap<>();

    // 存，写
    public void put(String key,Object value){
        System.out.println(Thread.currentThread().getName()+"写入："+key);
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"写入完毕："+key);
    }

    // 取，读
    public Object get(String key){
        System.out.println(Thread.currentThread().getName()+"读取："+key);
        Object obj = map.get(key);
        System.out.println(Thread.currentThread().getName()+"读取ok："+key);
        return obj;
    }
}

/**
 * 自定义缓存
 */
class MyCacheLock{
    private volatile Map<String,Object> map = new HashMap<>();
    // 读写锁：更加细粒度的控制
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    // 存，写   写入时，只希望同时只有一个线程写
    public void put(String key,Object value){
        
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"写入："+key);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入完毕："+key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }

    }

    // 取，读
    public Object get(String key){
        Object obj = null;
        readWriteLock.readLock().lock();

        try {
            System.out.println(Thread.currentThread().getName()+"读取："+key);
            obj = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取ok："+key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();
        }
        return obj;
    }
}